import { Button, VStack, Text, useMediaQuery } from '@chakra-ui/react';
import React, { useEffect, useState } from 'react';
import { useAppSelector } from '../../redux/hooks';
import useSocket from '../hooks/useSocket';

export default function AnswersOnQuestions(): JSX.Element {
  const { answerHandler } = useSocket();
  const { questions, currentAnswers, currentQuestionId } = useAppSelector((state) => state.game);
  const user = useAppSelector((store) => store.user);
  const [selectedAnswerId, setSelectedAnswerId] = useState<number | null>(null);

  // Добавляем media query для определения мобильного устройства
  const [isMobile] = useMediaQuery("(max-width: 480px)");

  const currentQuestion = questions[currentQuestionId];
  const rightAnswerID = currentQuestion?.rightAnswer;

  const handleAnswerClick = (answerId: number): void => {
    setSelectedAnswerId(answerId);
    answerHandler(answerId);
  };

  useEffect(() => {
    let audio: HTMLAudioElement | undefined;
    if (user.hasAnswer && selectedAnswerId !== null) {
      const audioPath =
        selectedAnswerId === rightAnswerID
          ? '/audio/correct.mp3'
          : '/audio/incorrect.mp3';
      audio = new Audio(audioPath);
      audio.play().catch((e) => console.error('Не удалось воспроизвести аудио', e));
    }

    return () => audio?.pause();
  }, [selectedAnswerId, rightAnswerID, user.hasAnswer]);

  const getButtonBackgroundColor = (answerId: number): string => {
    if (!user.hasAnswer) return 'yellow.400';
    return answerId === rightAnswerID ? 'green.400' : 'red.400';
  };

  const getButtonScale = (answerId: number): { [key: string]: string } => ({
    transform: selectedAnswerId === answerId ? 'scale(1.1)' : 'none',
    transition: 'transform 0.2s ease-in-out',
  });

  const getButtonShadow = (answerId: number): string =>
    selectedAnswerId === answerId ? '0px 4px 12px rgba(0, 0, 0, 0.15)' : 'none';

  const indexToLetter = (index: number): string => String.fromCharCode(65 + index);

  const remainingQuestions = questions.length - currentQuestionId - 1;

  return (
    <VStack
      spacing={6}
      p={5}
      border="2px solid"
      borderColor="teal.500"
      borderRadius="xl"
      boxShadow="2xl"
      bg="blue.200"
      width="full"
      maxWidth="1600px"
      m="0 auto"
      minHeight="60vh"
    >
      <Text fontSize={isMobile ? "2xl" : "3xl"} fontWeight="bold">
        Вопрос {currentQuestionId + 1} из {questions.length} (Осталось: {remainingQuestions})
      </Text>
      {currentQuestion ? (
        <>
          <Text fontSize={isMobile ? "2xl" : "5xl"} fontWeight="bold" textAlign="center" mb={4}>
            {currentQuestion.question}
          </Text>
          <VStack spacing={4} width="100%">
            {currentAnswers.map((answer, index) => (
              <Button
                key={answer.id}
                onClick={() => handleAnswerClick(answer.id)}
                isDisabled={user.hasAnswer}
                backgroundColor={getButtonBackgroundColor(answer.id)}
                _hover={{ bg: user.hasAnswer ? '' : 'yellow.500' }}
                sx={getButtonScale(answer.id)}
                boxShadow={getButtonShadow(answer.id)}
                size="lg"
                fontSize="2xl"
                py={10}
                px={12}
                width="90%" // Установка ширины кнопки на 100%
                border="1px solid black" // Добавление обводки вокруг кнопки черным цветом
              >
                {`${indexToLetter(index)}. ${answer.answer}`}
              </Button>
            ))}
          </VStack>
        </>
      ) : (
        <Text textAlign="center">Выберите тему для начала игры</Text>
      )}
    </VStack>
  );
}
